package org.github.project.observer;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 观察者对象
 * <p>
 * <span>
 * 观察者模式属于行为模式, 一个对象（被观察者）的状态发生改变,
 * 所有依赖的对象（观察者对象）都将得到通知, 进行<strong>广播通知</strong>。
 * </span>
 * <p>
 * 使用场景: 完成某件事情后, 异步通知场景。如, 登录成功后, 发送短信/邮箱消息。
 * <p>
 * 登录状态服务
 *
 * @auther yang
 * @date 2022/1/21 13:04
 */
@Service
public class LoginStateService implements ApplicationContextAware {

    public List<IMessageService> observers;


    public void setState(LoginStateEnum loginState) {
        // 这里添加设置一系列状态的逻辑（数据库存储...）

        this.notifyAllObservers(loginState);
    }

    private void notifyAllObservers(LoginStateEnum loginState) {
        this.observers.forEach(observer -> observer.send(loginState.getMsg()));
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.observers = applicationContext.getBeanProvider(IMessageService.class).stream().collect(Collectors.toList());
    }

    @Service
    public static class SmsService implements IMessageService {

        @Override
        public void send(String msg) {
            System.out.println("向手机发短信: " + msg);
        }
    }

    @Service
    public static class EmailService implements IMessageService {

        @Override
        public void send(String msg) {
            System.out.println("向邮箱发邮件: " + msg);
        }
    }
}
